﻿using System;
using System.Activities;
using System.Activities.DurableInstancing;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Web;

namespace MVCWorkflow.Models
{
public class WorkflowHost
{
    private WorkflowApplication app;
    private AutoResetEvent instanceUnloaded = new AutoResetEvent(false);

    public WorkflowHost(System.Activities.Activity activity)
    {
        var store = new SqlWorkflowInstanceStore(System.Configuration.ConfigurationManager.ConnectionStrings["WorkflowConnection"].ConnectionString);
        store.InstanceCompletionAction = InstanceCompletionAction.DeleteNothing;

        app = new WorkflowApplication(activity);
        app.InstanceStore = store;
        app.PersistableIdle = (e) =>
        {
            return PersistableIdleAction.Persist;
        };
        app.Completed = (e) =>
        {
            instanceUnloaded.Set();
        };
        app.Idle = (e) =>
        {
            instanceUnloaded.Set();
        };
    }

    public Guid Start()
    {
        app.Run();
        instanceUnloaded.WaitOne();

        return app.Id;
    }

    public void Run(Guid instanceId, object value)
    {
        string bookmarkName = app.GetBookmarks()[0].BookmarkName;
        var book = app.ResumeBookmark(bookmarkName, value);
        instanceUnloaded.WaitOne();
    }

    public void Resume(Guid instanceId)
    {
        app.Load(instanceId);
    }

    public void Unload()
    {
        app.Unload();
    }
}
}